/*
 * file_list_xml_maker.c
 *
 *  Created on: 2011-6-18
 *      Author: JustinLee
 */

#include <stdio.h>
#include <string.h>
#include "file_list_xml_maker.h"

#define MAX_ELEMENT_LEN 4096

#define STR_MOVIE_TYPES ".mpg.avi.wmv.mp4.rmvb.rm.mov.mkv.3gp.mkv.asf.flv.ts.mpeg2.m4v.f4v"
#define STR_AUDIO_TYPES ".mp3.aac.flac.ogg.midi.wav.pcm.ape.amr.wma.cda.f4a.m4a"
#define STR_PICTURE_TYPES ".bmp.jpg.jpeg.gif.png"


static char* XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<root>\r\n";
static char* XML_ENDER = "</root>\r\n";
static char* XML_ELEMENT_TEMPLATE = "\t<file_dir>\r\n\t<img>%s</img>\r\n\t<name>%s</name>\r\n\t<uri>%s%s</uri>\r\n\t</file_dir>\r\n";

typedef enum e_ICON_INDEX {
	EII_MOVIE = 0,
	EII_AUDIO,
	EII_PICTURE,
	EII_OTHER,
	EII_COUNT,
}ICON_INDEX;

static char* icon_array[EII_COUNT] = {FL_XML_MOVIE_ICON, FL_XML_AUDIO_ICON, FL_XML_PICTURE_ICON, FL_XML_OTHER_ICON};
static char* icon_class_array[EII_COUNT] = {STR_MOVIE_TYPES, STR_AUDIO_TYPES, STR_PICTURE_TYPES, ""};

static inline char* get_icon_by_name(char* name)
{
	int i = 0;
    char* init_name = name;
    char* last_name = NULL;
    while (name)
    {
        last_name = name;
        name = strstr(&name[1], ".");
    }
    if (last_name == init_name)
    {
        name = NULL;
    }
    else
    {
        name = last_name;
    }
    if(name)
	{
		for(i = 0; i < EII_OTHER; ++i)
		{
			if(strstr(icon_class_array[i], name))
			{
				return icon_array[i];
			}
		}
	}
	return icon_array[EII_OTHER];
}

bool make_file_list_xml(char* dst_path, FILE_INFO_LIST* list, char* url_prefix)
{
	FILE* hf = 0;
	char buf[MAX_ELEMENT_LEN] = {0};
	long cnt = 0;
	long i = 0;
	if(!dst_path || !list || !url_prefix)
	{
		return false;
	}
	hf = fopen(dst_path, "wb");
	if(hf <= 0)
	{
		return false;
	}
	fwrite(XML_HEADER,1,strlen(XML_HEADER),hf);
	while(list)
	{
		cnt = list->count;
		i = 0;
		while(cnt > 0)
		{
			sprintf(buf, XML_ELEMENT_TEMPLATE,
					get_icon_by_name(list->array[i].file_name),
					list->array[i].file_name,
					url_prefix,
					list->array[i].file_name
					);
			fwrite(buf,1,strlen(buf),hf);
			--cnt;
			++i;
		}
		list = list->next;
	}
	fwrite(XML_ENDER,1,strlen(XML_ENDER),hf);
	fclose(hf);
	return false;
}
